import React from 'react';
import ReactDOM from 'react-dom';
import {  WeaTools } from 'ecCom';
import WeaTableEdit from '../table-edit';
import { observer } from 'mobx-react';
import isFunction from 'lodash/isFunction';
import { toJS } from 'mobx';
import { Pagination } from 'antd';
import { removeHTMLTag, getListKey } from '../../util';
import $ from "jquery";

export interface EditorProps {
    comsWeaTableStore: any;
    getColumns?: (columns: any[]) => any[];
    tableWidth?: (columns: any[]) => string;
    needScroll?: boolean;
    rowKey?: (Record, index) => any;
    rowSelection?: any;
    hasOrder?: boolean;
    tableCheck?: boolean;
    pagination?: any;
    paginationFix?: boolean;
    onChange?: Function;
    locale?: any;
    heightSpace?: number;
    outerHeight?: number;
    editableColumns?: any;
    onDatasChange?: (datas: any[]) => void;
    onPaginationChange?:(p:any, f:any, s:any)=>void;
}
const defaultLocale = {
    total: '共',
    totalUnit: '条',
    operates: '操作',
    items_per_page: '条/页',
    jump_to: '跳至',
    page: '页',
    first_page: '第一页',
    last_page: '最后一页',
    prev_page: '上一页',
    next_page: '下一页',
    prev_5: '向前 5 页',
    next_5: '向后 5 页',
    customColTitle: '定制列',
    customColSelect: '待选列名',
    customColSelected: '已选列名',
    customColSave: '保存',
    customColCancel: '取消',
    loading: '加载中...',
};
@observer
export default class Editor extends React.Component<EditorProps, any> {
    constructor(props) {
        super(props)
        this.state = {
            //WeaTableEdit属性
            isModalEdit: false,
            height: 0,
            filters: {},
            sorter: {},
            pagination: {},
        }
    }
    componentDidMount() {
        this.scrollheigth();
        $(window).resize(() => {
            this.scrollheigth();
        });
    }
    getLocale() {
        let locale = {};
        if (this.context.antLocale && this.context.antLocale.Table) {
            locale = this.context.antLocale.WeaTable;
        }
        return { ...defaultLocale, ...locale, ...this.props.locale };
    }
    onChange = (datas) => {
        const { onDatasChange } = this.props
        onDatasChange && onDatasChange(datas);
    }
    onRowSelect = () => {
    }
   
    render() {
        const { comsWeaTableStore, getColumns, tableWidth, hasOrder, paginationFix } = this.props
        let columns = comsWeaTableStore.columns.slice().map(col => {
            return {
                ...col,
                com: [
                    { label: '', type: 'INPUT', editType: '1', key: col.dataIndex, width: 120, },
                ],
            }
        });
        const { height } = this.state;
        // fix by caoyun 修复完整深复制导致mobx下title不能传多子组件（形如<div><span>111</span><span>222</span></div>)的问题
        // let newColumns = cloneDeep(columns);
        let newColumns = columns.map((col) => {
            return { ...col };
        });
        if (getColumns) {
            newColumns = getColumns(newColumns);
        }

        let scrollWidth;
        if (tableWidth && isFunction(tableWidth)) {
            scrollWidth = tableWidth(newColumns);
        }
        newColumns = this.reComputeColumn(newColumns, hasOrder, comsWeaTableStore.sortParams);
        return (
            <div className="cube-edit-table">
                <div style={{ width: '100%', height: '100%' }}>
                    <div style={paginationFix ? { width: '100%', height: height + 45, overflowX: WeaTools.isBelowIE9() ? 'scroll' : 'auto' } : { width: '100%', overflowX: WeaTools.isBelowIE9() ? 'scroll' : 'auto' }}>
                        <div style={scrollWidth ? { width: scrollWidth, minWidth: '100%' } : { width: '100%' }}>
                            <WeaTableEdit
                                columns={newColumns}
                                datas={comsWeaTableStore.datas.slice()}
                                onChange={this.onChange}
                                onRowSelect={this.onRowSelect}
                                draggable={false}
                                showCopy={false}
                                showAdd={false}
                                showDelete={false}
                                tableProps={this.getTableProps()}
                                rowKey={getListKey}
                            />
                        </div>
                    </div>
                    <div className={`wea-table-pagination ${paginationFix && 'wea-table-pagination-fix'}`}>
                        <Pagination
                            className='ant-table-pagination'
                            {...this.getPagination() }
                        />
                    </div>
                </div>
            </div>
        )
    }
    getTableProps = () => {
        const { needScroll,onPaginationChange } = this.props;
        const { height } = this.state;
        let scrollHeight = needScroll ? { scroll: { y: height } } : {};
        return {
            onChange: onPaginationChange,
            ...scrollHeight
        }
    }
    getRowSel = () => {
        const { comsWeaTableStore, rowSelection = {} } = this.props;
        const { selectedRowKeys, rootMap } = comsWeaTableStore;
        let rowSel = {
            ...rowSelection,
            type: rootMap && rootMap.tabletype || 'checkbox',
            selectedRowKeys: toJS(selectedRowKeys),
            onChange(sRowKeys, selectedRows) {
                comsWeaTableStore.setSelectedRowKeys(sRowKeys);
                rowSelection && isFunction(rowSelection.onChange) && rowSelection.onChange(sRowKeys, selectedRows);
            },
            getCheckboxProps: (record) => {
                return { disabled: record["randomFieldCk"] !== "true" };
            }
        };

        return rowSel;
    }
    getPagination = () => {
        const { comsWeaTableStore } = this.props;
        const { count, current, size, pageSize, pageSizeOptions } = comsWeaTableStore;
        const locale = this.getLocale();
        let obj = {
            size: size ? size : {},
            pageSize: 0,
            current: 0,
            total: count,
            showTotal: (total) => {
                return `${locale.total} ${total} ${locale.totalUnit}`;
            },
            showSizeChanger: true,
            showQuickJumper: true,
            pageSizeOptions: Array.isArray(pageSizeOptions) ? pageSizeOptions : [10, 20, 50, 100],
            onShowSizeChange: (current, pageSize) => {
                let { pagination } = this.state,
                    { onPaginationChange } = this.props;
                pagination.current = current;
                pagination.pageSize = pageSize;
                this.setState({ pagination }, () => {
                    let { pagination, filters, sorter } = this.state;
                    typeof onPaginationChange == "function" && onPaginationChange(pagination, filters, sorter)
                })
            },
            onChange: current => {
                let { pagination } = this.state,
                    { onPaginationChange } = this.props;
                pagination.current = current;
                this.setState({ pagination }, () => {
                    let { pagination, filters, sorter } = this.state;
                    typeof onPaginationChange == "function" && onPaginationChange(pagination, filters, sorter)
                })
            },
            locale: locale
        };
        if (typeof pageSize !== 'undefined') {
            obj.pageSize = pageSize
        }
        if (typeof current !== 'undefined') {
            obj.current = current
        }
        return obj
    }
    onPaginationChange = (p, _, s) => {
        const { comsWeaTableStore } = this.props;
        comsWeaTableStore.getDatas(comsWeaTableStore.sessionkey, p.current, p.pageSize, s)
    }
    reComputeColumn = (newColumns, hasOrder, sortParams) => {
        const { editableColumns = {} } = this.props;
        let oldWidthObj = {}
        let nowWidth = 0;
        newColumns = newColumns.filter((newColumn) => {
            if (newColumn.display === "true") {
                const width = newColumn.oldWidth ? parseFloat(newColumn.oldWidth.substring(0, newColumn.oldWidth.length - 1)) : 10;
                oldWidthObj[newColumn.dataIndex] = width;
                nowWidth += width;
            }
            return newColumn.display === "true";
        });
        newColumns = newColumns.map((newColumn) => {
            if (newColumn.display === "true") {
                // 如果没有固定列宽，且不是自适应宽度，则按100%重新分配宽度
                newColumn.width = (
                    parseFloat(oldWidthObj[newColumn.dataIndex]) +
                    (100 - nowWidth) * parseFloat(`${oldWidthObj[newColumn.dataIndex] / nowWidth}`)
                ) + "%";
                if (hasOrder && newColumn.orderkey) {
                    newColumn.sorter = true;
                    if (sortParams && sortParams.length > 0) {
                        sortParams.map(s => {
                            if (s.orderkey == newColumn.orderkey)
                                newColumn.sortOrder = s.sortOrder;
                        });
                    } else {
                        newColumn.sortOrder = false;
                    }
                }
                if (`${newColumn.dataIndex}` in editableColumns) {
                    newColumn.com = editableColumns[`${newColumn.dataIndex}`];
                } else {
                    newColumn.render = (_, record) => { // 前端元素转义
                        const valueSpan = record[`${newColumn.dataIndex}span`] !== undefined
                            ? record[`${newColumn.dataIndex}span`] : record[newColumn.dataIndex];
                        return (
                            <div className='wea-url' title={removeHTMLTag(valueSpan)} dangerouslySetInnerHTML={{ __html: valueSpan }} />
                        );
                    };
                }
                return newColumn;
            }
            return newColumn;
        });
        return newColumns;
    }

    scrollheigth = (h = 0) => {
        // 针对弹出框中的table,增加outerHeight逻辑
        const { heightSpace, outerHeight } = this.props;
        let heightOther = heightSpace || 0;
        let thisDom = ReactDOM.findDOMNode(this);
        // let tableDom = jQuery(".wea-new-table");
        let tableDom = $(thisDom);
        if (tableDom && $(".ant-pagination.ant-table-pagination", tableDom)) {
            let widowClientHeight = outerHeight || document.documentElement.clientHeight || 0;
            let top = 0;
            if (outerHeight) {
                top = tableDom.position() ? tableDom.position().top : 0;
            } else {
                top = tableDom.offset() ? tableDom.offset().top : 0;
            }
            let titileHeight = $(".ant-table-header .ant-table-thead", tableDom).height() || 45;
            let bottom = ($(".ant-pagination.ant-table-pagination", tableDom).height() || 30) + 15;
            let scrollheigth = widowClientHeight - top - titileHeight - bottom;
            this.setState({
                height: scrollheigth - 15 - heightOther - h
            })
        }
    }
}